package com.kly.pay.service.impl;

import cn.hutool.core.codec.Base64;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fqgj.base.services.redis.RedisClient;
import com.fqgj.common.utils.StringUtils;
import com.kly.dto.ApplePayDto;
import com.kly.dto.AppleVipInfoDto;
import com.kly.pay.bo.ApplePay;
import com.kly.pay.bo.ApplePayReceipt;
import com.kly.service.pay.ApplePayService;
import com.kly.util.ApplePayUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service("applePayService")
public class ApplePayServiceImpl implements ApplePayService {


    @Resource
    RedisClient redisClient;


    private final static String APPLE_VIP_KEY = "apple_vip_key_{}";


    public Integer notifyOfApplePay(ApplePayDto applePayDTO) {
        log.info("苹果支付结果通知::" + JSONObject.toJSONString(applePayDTO));
        Integer result = 0;
        try {
            //1.先线上测试    发送平台验证
            String pay = ApplePayUtil.buyAppVerify(applePayDTO.getTransactionReceipt(), applePayDTO.getType());
            log.info("APPLEPAY校验返回::" + pay);
            // 苹果服务器没有返回验证结果
            if (pay == null) {
//            ResultUtil.fail(801, "无订单信息");
            } else {
                // 苹果验证有返回结果
                ApplePay applePay = JSON.parseObject(pay, ApplePay.class);
                if ("21007".equals(applePay.getStatus())) {
                    //是沙盒环境，应沙盒测试，否则执行下面
                    log.info("苹果支付进入沙盒模式");
                    pay = ApplePayUtil.buyAppVerify(applePayDTO.getTransactionReceipt(), 0);
                    applePay = JSON.parseObject(pay, ApplePay.class);
                }

                // 前端所提供的收据是有效的    验证成功
                if ("0".equals(applePay.getStatus())) {
                    ApplePayReceipt receipt = applePay.getReceipt();

//                    System.out.println("APPLEPAY回调信息：：" + JSONObject.toJSONString(receipt));
//                    String decode = cn.hutool.core.codec.Base64.decodeStr(applePayDTO.getTransactionReceipt());
//                    decode = decode.replace("\" = \"", "\":\"");
//                    decode = decode.replace("\";", "\",");
//                    JSONObject appleObj = JSONObject.parseObject(decode);
//                    if (appleObj.containsKey("environment") &&
//                            appleObj.getString("environment").equals("Sandbox")) {
//                        log.info("苹果支付回执信息来自沙盒模式");
//                    }
//                    String purchaseInfo = Base64.decodeStr(appleObj.getString("purchase-info"));
//                    purchaseInfo = purchaseInfo.replace("\" = \"", "\":\"");
//                    purchaseInfo = purchaseInfo.replace("\";", "\",");
//                    JSONObject purchaseObj = JSONObject.parseObject(purchaseInfo);
//                    log.info("解析数据：" + purchaseObj);
//
//                    //如果单号一致  则开始处理逻辑
//                    if (purchaseObj.getString("transaction-id").equals(receipt.getTransaction_id())
//                            && purchaseObj.getString("unique-identifier").equals(receipt.getUnique_identifier())
//                            && purchaseObj.getString("purchase-date-ms").equals(receipt.getPurchase_date_ms())) {
//                        Map<String, String> orderInfoMap = new HashMap<>();
//                        orderInfoMap.put("payAccount", purchaseObj.getString("product-id"));
//                        orderInfoMap.put("tradeNo", applePayDTO.getTradeNo());
//                        orderInfoMap.put("payChannel", "3");
//                        orderInfoMap.put("payTime", purchaseObj.getString("purchase-date-ms"));
//                        orderInfoMap.put("externalId", receipt.getTransaction_id());
//                        orderInfoMap.put("remark", JSONObject.toJSONString(receipt));
//                        doPaySuccessThing(orderInfoMap);

                        LocalDate today = LocalDate.now(); // 获取今天的日期
                        LocalDate thirtyDaysLater = today.plusDays(30);
                        DateTimeFormatter nowFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
                        String nowDate = thirtyDaysLater.format(nowFormatter);
                        redisClient.set(APPLE_VIP_KEY, nowDate, 30 * 24 * 60 * 60, applePayDTO.getUserCode());
                        result = 1;
//                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    @Override
    public AppleVipInfoDto getAppleVipFlag(String userCode) {
        AppleVipInfoDto appleVipInfoDto=new AppleVipInfoDto();
        appleVipInfoDto.setVipFlag(false);
        String vip = redisClient.get(APPLE_VIP_KEY, userCode);
        if (!StringUtils.isEmpty(vip)) {
            appleVipInfoDto.setVipFlag(true);
            appleVipInfoDto.setEndDate(vip);
        }
        return appleVipInfoDto;
    }

}
